<?php

namespace App\Http\Controllers\Admin;

use App\AdminUser;
use App\Http\Controllers\Controller;
use App\Traits\ApiResponse;
use Illuminate\Foundation\Auth\RedirectsUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Http\Request;
use Auth;

class AuthController extends Controller
{
    use ApiResponse;
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
     */

    use RedirectsUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectirectTo = '/admin';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
//        $this->middleware('guest')->except('logout', 'updatePassword', 'user');
    }

    public function user(Request $request)
    {
        return $this->success([
            'user' => $request->user('admin'),
        ]);
    }

    public function loginForm()
    {
        return view('admin.auth.login');
    }

    public function login(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string',
            'password' => 'required|string',
        ], [
        ]);
        if ($this->hasTooManyLoginAttempts($request)) {
            // if (!$request->session()->has('use_captcha') || $request->session()->get('use_captcha') === false) {
            //     return redirect('/admin/login');
            // }
            // $this->fireLockoutEvent($request);
            // return $this->sendLockoutResponse($request);
        }

        if (!$this->attemptLogin($request)) {
            $this->incrementLoginAttempts($request);
            return $this->error('用户名或密码错误');
        }
        $this->clearLoginAttempts($request);
        return $this->success([
            'user' => $request->user('admin'),
        ], '登陆成功');
    }


    /**
     * Attempt to log the user into the application.
     *
     * @param \Illuminate\Http\Request $request
     * @return bool
     */
    protected function attemptLogin(Request $request)
    {
//        if (!AdminUser::where($this->username(), $request->input('name'))->first()) {
//            return false;
//        }
        return $this->guard()->attempt(
            $this->credentials($request), $request->has('remember')
        );
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        return [
            $this->username() => $request->input('name'),
            'password' => $request->input('password'),
        ];
        return $request->only($this->username(), 'password');
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
    }

    /**
     * The user has been authenticated.
     *
     * @param \Illuminate\Http\Request $request
     * @param mixed $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        //
    }

    /**
     * Get the failed login response instance.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        $errors = ['name' => trans('auth.failed')];

        if ($request->expectsJson()) {
            return response()->json($errors, 422);
        }

        return redirect()->back()
            ->withInput($request->only('name', 'remember'))
            ->withErrors($errors);
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        $value = request()->input('name', '');
        if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
            return 'email';
        }
        if (filter_var($value, FILTER_VALIDATE_INT) && strlen($value) == 11) {
            return 'phone_number';
        }
        return 'name';
    }

    /**
     * Log the user out of the application.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->invalidate();

        if ($request->ajax()) {
            return $this->success();
        }
        return redirect(route('admin.login'));
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard('admin');
    }

    public function redirectPath()
    {
        if (request()->input('redirect_url', '')) {
            return request()->input('redirect_url', '');
        }
        return '/admin';
    }

    public function updatePassword(Request $request)
    {
        $this->validate($request, [
            'old_password' => 'required|string|max:25',
            'password' => 'required|string|max:25|confirmed',
        ]);
        if (!$this->guard()->attempt(['username' => $request->user()->username, 'password' => $request->input('old_password')])) {
            return response()->json(['status' => 'error', 'message' => '原密码错误']);
        }
        $user = $request->user();
        $user->password = bcrypt($request->input('password'));
        if (!$user->save()) {
            return response()->json(['status' => 'error', 'message' => '服务器错误']);
        }
        return response()->json(['status' => 'success', 'message' => '修改成功']);
    }

}
